package com.asset.modules.assets.controller;

import com.alibaba.fastjson.JSON;
import com.asset.modules.assets.model.Asset;
import com.asset.modules.assets.service.impl.AssetServiceImpl;
import com.asset.modules.common.model.DownloadBean;
import com.asset.modules.common.model.ResponseBean;
import com.asset.modules.common.model.UglyBean;
import com.asset.modules.common.handler.AssetListener;
import com.asset.modules.common.servcie.ExcelService;
import com.asset.modules.common.utils.Constant;
import com.asset.modules.common.utils.DateUtils;
import com.asset.modules.common.utils.StringUtil;
import com.asset.modules.system.model.Company;
import com.asset.modules.system.model.Project;
import com.asset.modules.system.service.CompanyService;
import com.asset.modules.system.service.ProjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenchen
 */
@RestController
@CrossOrigin
@RequestMapping("/asset")
@Api(tags = "固定资产接口")
public class AssetController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AssetController.class);

    @Autowired
    private AssetServiceImpl as;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private ProjectService ps;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private CompanyService cs;

    @ApiOperation(value = "固资信息保存和更新")
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    public ResponseBean saveOrUpdate(@RequestBody Asset asset){
        try{
            boolean flag = as.mySaveOrUpdate(asset);
            return new ResponseBean(HttpStatus.OK.value(), "操作成功！", flag);
        }catch (Exception e){
            LOGGER.error("保存或更新失败,失败信息为{}", e.getMessage());
            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), Constant.FAILED_OPERATION,false);
        }

    }



    @ApiOperation(value = "根据ID获取固资信息")
    @RequestMapping(value = "/byId", method = RequestMethod.GET)
    public ResponseBean getAssetById(@RequestParam String id){
        Asset asset = as.getById(id);
        Project p   = ps.getById(asset.getProjectId());
        Company c   = cs.getById(p.getCompanyId());
        asset.setProjectCode(p.getProjectCode());
        asset.setProjectName(p.getProjectName());
        asset.setCompanyCode(c.getCompanyCode());
        asset.setCompanyName(c.getCompanyName());
        return new ResponseBean(HttpStatus.OK.value(), "操作成功!", asset);
    }


    @ApiOperation(value = "根据code获取固资信息")
    @RequestMapping(value = "/byCode", method = RequestMethod.GET)
    public ResponseBean getAssetByCode(@RequestParam String code){
        QueryWrapper<Asset> qw = new QueryWrapper<>();
        qw.eq("manage_code", code);
        Asset asset = as.getOne(qw);
        Project p   = ps.getById(asset.getProjectId());
        Company c   = cs.getById(p.getCompanyId());
        asset.setProjectCode(p.getProjectCode());
        asset.setProjectName(p.getCompanyName());
        asset.setCompanyCode(c.getCompanyCode());
        asset.setCompanyName(c.getCompanyName());
        return new ResponseBean(HttpStatus.OK.value(), "操作成功!", asset);
    }


    /**
     * 获取固资分页
     * @param uglyBean
     * @return
     */
    @ApiOperation(value = "固资分页", notes = "page对象，设置current(当前页), size(每页显示条数))，" +
            "Asset对象中状态的不同，结果就不同：" +
            "1.类为已盘点、未盘点为正常固定资产" +
            "2.类型为报废，为报废物品分页信息" +
            "3.类型为已盘点、未盘点并且净值<=2000的为低值易耗品")

    @RequestMapping(value = "/getPages", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getAssetPages(@RequestBody UglyBean uglyBean){
        Page page = JSON.parseObject(uglyBean.getPage(), Page.class);
        Asset asset = JSON.parseObject(uglyBean.getAnything(), Asset.class);
        IPage<Asset> pages = null;
        try{
            pages = as.getAssetPage(page, asset);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(pages==null){
            return new ResponseBean(HttpStatus.OK.value(), "请求成功", "查询结果为空！");
        }
        return new ResponseBean(HttpStatus.OK.value(), "请求成功", pages);
    }


    /**
     * 获取报废物品分页
     * @param uglyBean
     * @return
     */
    @ApiOperation(value = "报废物品分页", notes = "page对象，设置current(当前页), size(每页显示条数)), Asset对象设置查询条件")
    @RequestMapping(value = "/getDiscardPages", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getDiscardPage(@RequestBody UglyBean uglyBean){
        Page page = null;
        try{
            page = JSON.parseObject(uglyBean.getPage(), Page.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        Asset asset = JSON.parseObject(uglyBean.getAnything(), Asset.class);
        return new ResponseBean(HttpStatus.OK.value(), "请求成功", as.getDiscardPage(page, asset));
    }

    /**
     * 获取低值易耗品分页
     * @param uglyBean
     * @return
     */
    @ApiOperation(value = "低值易耗品分页", notes =  "page对象，设置current(当前页), size(每页显示条数)), Asset对象，设置查询条件")
    @RequestMapping(value = "/getLowValuePages", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean getLowValuePage(@RequestBody UglyBean uglyBean){
        Page page = JSON.parseObject(uglyBean.getPage(), Page.class);
        Asset asset = JSON.parseObject(uglyBean.getAnything(), Asset.class);
        return new ResponseBean(HttpStatus.OK.value(), "请求成功", as.getLowValuePage(page, asset));
    }


    @ApiOperation(value = "删除固资信息")
    @RequestMapping(value = "/remove", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean removeAsset(@RequestParam String ids){
        String msg ="";
        if(StringUtil.isBlank(ids)){
            msg  = "待删除固资ID为空";
        }
        String[] removeIds = ids.split(",");
        List list = new ArrayList();
        for(String id : removeIds){
            list.add(id);
        }
        boolean flag;
        try{
             flag = as.removeByIds(list);
             msg  = "操作成功";
        }catch (Exception e){
            flag = false;
            msg  ="删除失败，请查看参数是否正确";
            e.printStackTrace();
        }
        return new ResponseBean(HttpStatus.OK.value(), msg, flag);
    }


    @ApiOperation(value="Excel文件上传", notes = "参数为MultipartFile对象, sheetNo表示sheet下标，headRowNum表示从第几行开始读正文，下标都是从0开始")
    @RequestMapping(value = "/uploadByFile", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean upLoadExcel(MultipartFile file, String sheetNo, int headRowNum){
        String result = null;
        if(sheetNo.equals(Constant.discardStatus)){
            result = excelService.readAllExcel(file, Asset.class, new AssetListener(ps, as), headRowNum);
        }else{
            result =  excelService.readExcel(file, Asset.class, new AssetListener(ps, as), Integer.valueOf(sheetNo), headRowNum);
        }
        return new ResponseBean(HttpStatus.OK.value(), "操作成功", result);
    }


    @ApiOperation(value="Excel文件上传", notes = "filePath：文件路径; sheetNo:sheet下标从0开始; sheetName: sheet名称，与sheetNo填一个即可；startNum Excel开始读取内容的位置")
    @RequestMapping(value = "/uploadByPath", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBean upLoadExcel(@RequestParam String filePath, @RequestParam int sheetNo, @RequestParam int startNum){
        String result =  excelService.readExcel(filePath, Asset.class,new AssetListener(ps, as),sheetNo, null, startNum);
        return new ResponseBean(HttpStatus.OK.value(), "操作成功", result);
    }



    @ApiOperation(value = "Excel文件下载")
    @RequestMapping(value = "/download", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean downloadAssetExcel(@RequestBody DownloadBean bean){
        long size = bean.getSize();
        Asset a   =   JSON.parseObject(bean.getAnything(), Asset.class);
        String fileName;
        String sheetName;
        String timestamp = DateUtils.getDateTimeNowStr();
        ResponseBean rb  = new ResponseBean();
        int startPage = bean.getStartPage();
        int endPage   = bean.getEndPage();
        fileName = bean.getFileName().isEmpty() ? "temp"+timestamp :  bean.getFileName();
        sheetName = bean.getSheetName().isEmpty() ? "temp"+timestamp :  bean.getSheetName();
        response.setContentType("mutipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xls");
        if(bean.getData().size()!=0){
            excelService.writeExcel(response, Asset.class, sheetName, bean.getData());
            rb.setCode(HttpStatus.OK.value());
            rb.setMsg("下载成功！");
        }else if(startPage>endPage){
           rb.setMsg("error, 开始页不能大于结束页");
           rb.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
           rb.setData(null);
        }else {
            excelService.writeExcel(response,  a,  sheetName, startPage, endPage, size);
            rb.setMsg("下载成功！");
            rb.setCode(HttpStatus.OK.value());
        }
        return rb;
    }

}
